package com.mystudy.netty.echo.version_1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.jar.Attributes;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/10/23 22:00
 * @Description 业务处理回调类
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        LOGGER.debug("server received = [{}] channel =[{}]", buf.toString(Charset.defaultCharset()),ctx.channel());
        ctx.write(buf);
        ctx.channel().write(Unpooled.copiedBuffer("测试output".getBytes()));
        this.userEventTriggered(ctx,new Student("周志龙",24));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //写完以后关闭channel
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.debug("error = [{}]",cause);
        ctx.close();
    }
}
